#include "stdafx.h"
#include "SimulationThread.h"

namespace AirCrash {
namespace Calypso {
		
SimulationThread::SimulationThread() : QThread(), mInterrupted(false) {
}

SimulationThread::~SimulationThread() {
}

void SimulationThread::run() {
	qDebug() << "Start Simulation";
	mInterrupted = false;
	QThread::sleep(10);
	while (!mInterrupted) {
		emit changePage(2);
		insertPage();
		if (mInterrupted) break;
		emit generateCodes();
		QThread::sleep(10);
		if (mInterrupted) break;
		emit changePage(1);
		tombolaPage();
	}
}

void SimulationThread::insertPage() {
	qsrand(QDateTime::currentMSecsSinceEpoch());
	int maxItems(Config::get("Simulation", "maxItems").toInt()),
		minItems(Config::get("Simulation", "minItems").toInt()),
		numItems( ((qrand() / (float)RAND_MAX) * (maxItems - minItems)) + minItems ),
		jackpot((qrand() / (float)RAND_MAX) * numItems);

	qDebug() << "Insert " << numItems << " Items";

	for (int x(0); x < numItems && !mInterrupted; ++x) {
		QMutexLocker lock(&mMutex);
		if (x == jackpot) {
			QString summary("Price " + QString::number(x) + " - Jackpot");
			emit fillInsertPage(1, 1, 1, summary, true);
		} else {
			int friday((qrand() / (float)RAND_MAX) * Config::get("Simulation", "maxFriday").toInt()),
				saturday((qrand() / (float)RAND_MAX) * Config::get("Simulation", "maxSaturday").toInt()),
				sunday((qrand() / (float)RAND_MAX) * Config::get("Simulation", "maxSunday").toInt());
			QString summary("Price " + QString::number(x));
			emit fillInsertPage(friday, saturday, sunday, summary, false);
		}
		QThread::sleep(2);
		emit createItem();
		mWait.wait(&mMutex);
		if (!mInterrupted) QThread::sleep(2);
	}
}

void SimulationThread::tombolaPage() {
	qDebug() << "Start Tombola sim";
	qsrand(QDateTime::currentMSecsSinceEpoch());
	int maxTombolaInserts(Config::get("Simulation", "maxTombolaInserts").toInt()),
		maxTombolaNumber(Config::get("Simulation", "maxTombolaNumber").toInt());

	for (int t(0); t < maxTombolaInserts && !mInterrupted; ++t) {
		int randNum((qrand() / (float)RAND_MAX) * maxTombolaNumber);
		mCode = QString::number(randNum);
		emit enterCode(mCode);
		QThread::sleep(2);
		emit getCode();
		if (!mInterrupted) QThread::sleep(10);
	}
}

void SimulationThread::nextItem() {
	mWait.wakeAll();
}

void SimulationThread::interrupt() {
	mWait.wakeAll();
	mInterrupted = true;
}

}
}